package org.yunai.yfserver.message;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.yunai.yfserver.common.LoggerFactory;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 消息队列，使用{@link java.util.concurrent.BlockingQueue}实现
 *
 * @see java.util.concurrent.BlockingQueue
 * User: yunai
 * Date: 13-4-23
 * Time: 下午10:23
 */
public class MessageQueue {

    private static final Logger LOGGER = LoggerFactory.getLogger(LoggerFactory.Logger.msg, MessageQueue.class);

    /**
     * 消息队列
     */
    private BlockingQueue<IMessage> msgQueue = new LinkedBlockingQueue<IMessage>();

    /**
     * 添加消息到消息队列
     * @param msg 消息
     */
    public void put(IMessage msg) {
        if (msg == null) {
            return;
        }
        try {
            msgQueue.put(msg);
        } catch (InterruptedException e) {
            LOGGER.error("[put] [error:{}].", ExceptionUtils.getStackTrace(e));
        }
    }

    public IMessage get() {
        if (isEmpty()) {
            return null;
        }
        try {
            return msgQueue.take();
        } catch (InterruptedException e) {
            LOGGER.error("[get] [error:{}].", ExceptionUtils.getStackTrace(e));
            return null;
        }
    }

    /**
     * @return 消息队列是否为空
     */
    public boolean isEmpty() {
        return msgQueue.isEmpty();
    }

    /**
     * @return 消息长度
     */
    public int size() {
        return msgQueue.size();
    }
}
